<?php
/**
 * api 财务
 */
namespace app\api\controller;
use app\api\model\BaseConfig as BaseConfigModel;
use app\api\model\Member as MemberModel;
use app\api\model\MemberTransfer as MemberTransferModel;
use app\api\model\MemberWithdrawal as MemberWithdrawalModel;
use app\common\common;
use app\common\model\MemberCurrency as MemberCurrencyModel;
use app\common\model\UserMoneyLog as UserMoneyLogModel;
use think\facade\Db;
use app\common\model\BlockchainOrder as BlockchainOrderModel;
use app\api\model\AdcLog as AdcLogModel;
use app\common\model\ContractAuthorization as ContractAuthorizationModel;

class Finance extends Baek
{
    /**
     * 财务参数
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function finance_config(){
        $data = [];
        //提现手续费类型 1:% 2:固定 扣得是U
//        $data['withdrawal_money_type'] = BaseConfigModel::config_data('withdrawal_money_type');
//        //提现手续费 扣得是U
//        $data['withdrawal_money'] = BaseConfigModel::config_data('withdrawal_money');
//        //最低提现金额
//        $data['min_withdrawal'] = BaseConfigModel::config_data('min_withdrawal');
//
//
//        //U转账手续费类型 1:% 2:固定 扣得是U
//        $data['accounts_withdrawal_type']   = BaseConfigModel::config_data('accounts_withdrawal_type');
//        //u转账手续费
//        $data['accounts_withdrawal'] = BaseConfigModel::config_data('accounts_withdrawal');
//        //adc转账手续费%
//        $data['adc_accounts_withdrawal'] = BaseConfigModel::config_data('adc_accounts_withdrawal');
//        //最低转账金额
//        $data['min_accounts'] = BaseConfigModel::config_data('min_accounts');
//
//
//        //USDT 兑换美金
//        $data['usdt_exchange'] = BaseConfigModel::config_data('usdt_exchange');
//        //LCC 兑换美金
//        $data['lcc_exchange'] = BaseConfigModel::config_data('lcc_exchange');
//        //ADC 兑换美金
//        $data['adc_exchange'] = BaseConfigModel::config_data('adc_exchange');

        return api_success($data);
    }

    /**
     * 提现
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function withdrawal(){
        $money  = $this->request->post('money', '', 'intval');
        $address = $this->request->post('address', '', 'serach_in');
        $chain_id = $this->request->post('chain_id', 1, 'intval');  //链地址ID
        $password = $this->request->post('password', '', 'serach_in');  //密码

        //验证密码
        if(!MemberModel::verify_password($this->mid,$password)) return api_error('','Password error',$this->language);

        //判断提现地址
        if(empty($address)) return api_error('','The withdrawal address is missing',$this->language);
        //判断提现数量
        if($money <= 0) return api_error('','Missing parameter',$this->language);

        //最低提现金额
        $min_withdrawal = BaseConfigModel::config_data('min_withdrawal');

        //判断金额提现是否低于系统设置
        if($min_withdrawal > $money) return api_error('','The withdrawal amount shall not be less than the limit',$this->language);

        //读取用户钱包
        $waller = MemberModel::wallet($this->mid)['waller'];

        //手续费类型
        $withdrawal_money_type = BaseConfigModel::config_data('withdrawal_money_type');
        //提现手续费 % or 固定值
        $withdrawal_money = BaseConfigModel::config_data('withdrawal_money');

        //计算手续费
        if($withdrawal_money_type == 1){
            $withdrawal_money = bcdiv($withdrawal_money,100,8); //抽成手续费 ÷ 100
            $deduction_money = bcmul($money,$withdrawal_money,8);
        }else{
            $deduction_money = $withdrawal_money;
        }

        $currency = 'USDT';
        //判断用户余额
        if($waller[1]['money'] < bcadd($deduction_money,$money)) return api_error('','Sorry, your credit is running low',$this->language);



        Db::startTrans();
        try {
            //添加提现记录
            $id = MemberWithdrawalModel::add_withdrawal($this->mid,$address,$money,1,$deduction_money,$chain_id);
            if(empty($id)){
                Db::rollback();
                return api_error('','Withdrawal failed',$this->language);
            }
            //扣除币种
            $pay_status = UserMoneyLogModel::change($this->mid,$currency,-$money,'withdrawal',$id,'提现：'.$money);
            if($pay_status != true){  //支付失败
                Db::rollback();
                return api_error($pay_status,'Withdrawal failed',$this->language);
            }
            if($deduction_money > 0){
                //扣除手续费
                $deduction_status = UserMoneyLogModel::change($this->mid,$currency,-$deduction_money,'Miners fee',$id,'提现：'.$money.',扣除手续费:'.$deduction_money);

                if($deduction_status != true){  //支付失败
                    Db::rollback();
                    return api_error($deduction_status,'Withdrawal failed',$this->language);
                }
            }

            //提交事务
            Db::commit();
            return api_success('');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return api_error('','Withdrawal failed',$this->language);
        }
    }

    /**
     * 提现记录列表
     * @return \think\Response
     * @throws \think\db\exception\DbException
     */
    function withdrawal_log(){
        $where['mid'] = $this->mid;
        $page  = $this->request->post('page', 1, 'intval');
        $limit = $this->request->post('limit', 20, 'intval');
        $where['status'] = $this->request->post('status', 0, 'intval');
        $where['chain_id'] = $this->request->post('chain_id', 1, 'intval');
        if($where['status'] == 0) unset($where['status']);
        $order = 'update_time desc,id desc';

        $data = MemberWithdrawalModel::getList(formatWhere($where),$page,$limit,$order);

        return api_success($data);
    }

    /**
     * 转账
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function transfer_accounts(){
        $money  = $this->request->post('money', '', 'intval');  //转账金额
        $type = $this->request->post('type', '', 'intval'); //转账币种
        $address = $this->request->post('address', '', 'serach_in');    //接收转账地址
        $remarks = $this->request->post('remarks', '', 'serach_in');    //备注
//        $password = $this->request->post('password', '', 'serach_in');  //密码

//        $member = MemberModel::password($this->mid)->toArray();
//        if(md5($password) != $member['password']) return api_error('','Password error',$this->language);

        $receive_member = MemberModel::address($address);
        if(empty($receive_member)) return api_error('','Collection user does not exist',$this->language);
        if($receive_member['id'] == $this->mid) return api_error('','The current transfer address is yourself',$this->language);

        //判断提现金额和金额类型
        if(empty($money) || empty($type)) return api_error('','Missing parameter',$this->language);
        //判断提现地址
        if(empty($address)) return api_error('','Missing collection address',$this->language);
        //判断提现数量
        if($money <= 0) return api_error('','Missing parameter',$this->language);
        //没有币种
        if($type!=1&&$type!=2&&$type!=5) return api_error('','Missing parameter',$this->language);
        //币种
        $currency = common::key_currency($type);

        //最低转账金额
        $min_accounts = BaseConfigModel::config_data('min_accounts');
        //判断转账金额是否低于系统设置
        if($min_accounts > $money) return api_error('','Transfer amount shall not be less than the limi',$this->language);

        //读取用户钱包
        $waller = MemberModel::wallet($this->mid);

        $deduction_money = 0;
        switch ($type){ //判断币种
            case 1:
                $accounts_withdrawal_type = BaseConfigModel::config_data('accounts_withdrawal_type');
                $accounts_withdrawal = BaseConfigModel::config_data('accounts_withdrawal');
                if($accounts_withdrawal_type == 1){ //转账手续费 %
                    $accounts_withdrawal = bcdiv($accounts_withdrawal,100,8); //抽成手续费 ÷ 100
                    //计算手续费
                    $deduction_money = bcmul($money,$accounts_withdrawal,8);
                }else{
                    $deduction_money = $accounts_withdrawal;
                }
                break;
            case 5:
                //转账手续费 %
                $accounts_withdrawal = BaseConfigModel::config_data('adc_accounts_withdrawal');
                $accounts_withdrawal = bcdiv($accounts_withdrawal,100,8); //抽成手续费 ÷ 100
                //计算手续费
                $deduction_money = bcmul($money,$accounts_withdrawal,8);
                break;
        }

        //判断用户余额
//        if($currency == 'adc'){
            if($waller[$currency] < bcadd($deduction_money,$money,8)) return api_error('','Sorry, your credit is running low',$this->language);
//        }else{
//            if($waller[$currency] < $deduction_money) return api_error('','Sorry, your credit is running low',$this->language);
//        }

        Db::startTrans();
        try {
            //执行转账
            $id = MemberTransferModel::add_transfer($this->mid,$type,$money,$address,$receive_member['id'],$deduction_money,$remarks);
            if(!$id) return api_error('','Transfer failed',$this->language);

            // 提交事务
            Db::commit();
            return api_success();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return api_error('','Transfer failed',$this->language);
        }
    }

    /**
     * 转账记录
     * @return \think\Response
     * @throws \think\db\exception\DbException
     */
    function transfer_log(){
        $where['mid|receive_mid'] = $this->mid;
        $page  = $this->request->post('page', 1, 'intval');
        $limit = $this->request->post('limit', 20, 'intval');
        //转账币种
        $where['currency'] = $this->request->post('currency', 0, 'intval');
        //接收方用户地址
        $where['address'] = ['like',$this->request->post('address', '', 'serach_in')];
        if($where['currency'] == 0) unset($where['currency']);

        $data = MemberTransferModel::getList(formatWhere($where),$page,$limit,'id desc');

        foreach ($data['data'] as $k => $v){
            $data['data'][$k]['currency'] = common::key_currency($v['currency']);
            $data['data'][$k]['type'] = $this->mid == $v['mid'] ? 1 : 2;
        }

        return api_success($data);
    }

    /**
     * 资金变化表
     */
    function capital_log(){
        $where['mid'] = $this->mid;
        $page  = $this->request->post('page', 1, 'intval');
        $limit = $this->request->post('limit', 20, 'intval');
        //币种
        $currency = $this->request->post('currency', 0, 'serach_in');
        if($currency!=0) $where['cid'] = ['in',$currency];
        //来源
        $type = $this->request->post('type', '', 'serach_in');
        if(!empty($type)) $where['type'] = ['in',$type];

        // 1:增加 2:减少
        $where['status'] = $this->request->post('status', 0, 'intval');
        if($where['status'] == 0) unset($where['status']);

        // $address = $this->request->post('address', '', 'serach_in');
        // if(!empty($address)){
        //     $member = MemberModel::address($address);
        //     if(empty($member)){
        //         $where['mid'] = 0;
        //     }else{
        //         $where['mid'] = $member->id;
        //     }
        // }

        $data = UserMoneyLogModel::getApiList(formatWhere($where),$page,$limit,'id desc',$this->language);

        $type_list = [];
        foreach (config('capital') as $k => $v){
            $type_list[$v[$this->language]] = $k;
        }
        $data['type'] =  $type_list;
        return api_success($data);
    }

    /**
     * 区块链订单添加
     * @return \think\Response
     */
    function paid(){
        $txhash = $this->request->post('txhash', '', 'serach_in');    //订单号
        $currency = $this->request->post('currency', 1, 'intval');    //支付币种        1:usdt  2:lcc 5:adc
        $type = $this->request->post('type', '', 'serach_in');    //支付类型
        $association_id = $this->request->post('id', '', 'intval');    //操作ID

        Db::startTrans();
        try {
            $id = BlockchainOrderModel::add($this->mid,$txhash,$currency,$type,$association_id);
            if(!$id) return api_error('','Blockchain order addition failed',$this->language);
            if(!is_numeric($id)) return api_error('',$id,$this->language);

            // 提交事务
            Db::commit();
            return api_success();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return api_error('','Blockchain order addition failed',$this->language);
        }
    }

    /**
     * ADC总流水记录
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function adc_log(){
        $where['mid'] = $this->mid;
        $page  = $this->request->post('page', 1, 'intval');
        $limit = $this->request->post('limit', 20, 'intval');
        //来源
        $where['type'] = $this->request->post('type', '', 'serach_in');

        $address = $this->request->post('address', '', 'serach_in');
        if(!empty($address)){
            $member = MemberModel::address($address);
            if(empty($member)){
                $where['mid'] = 0;
            }else{
                $where['mid'] = $member->id;
            }
        }

        $data = AdcLogModel::getApiList(formatWhere($where),$page,$limit,'add_time desc',$this->language);

        if(!empty($address)){

            $sys_swap =    'ADCswap000000000000000000000000000000000';  //交易系统
            $sys_address = 'ADC0000000000000000000000000000000000000';  //系统方

            foreach ($data['data'] as $k => $v){

                switch ($v['type']){
                    case 'transfer':    //转账
                        $MemberTrans = MemberTransferModel::getDetails($v['relation_id']);
                        $receive = MemberModel::getDetails($MemberTrans['receive_mid']);
                        $data['data'][$k]['send_address'] = $receive->username;
                        $data['data'][$k]['receive_address'] = $MemberTrans['address'];

                        break;
                    case 'Transaction sell':    //交易    交易賣出
                        if($v['num'] < 0){  //支出
                            $data['data'][$k]['send_address'] = $member->username;
                            $data['data'][$k]['receive_address'] = $sys_swap;
                            $data['data'][$k]['num'] = -$v['num'];
                        }else{  //收入
                            $data['data'][$k]['send_address'] = $sys_swap;
                            $data['data'][$k]['receive_address'] = $member->username;
                        }
                        break;
                    case 'Transaction cancellation':    //交易    交易撤銷
                        if($v['num'] < 0){  //支出
                            $data['data'][$k]['send_address'] = $member->username;
                            $data['data'][$k]['receive_address'] = $sys_swap;
                            $data['data'][$k]['num'] = -$v['num'];
                        }else{  //收入
                            $data['data'][$k]['send_address'] = $sys_swap;
                            $data['data'][$k]['receive_address'] = $member->username;
                        }
                        break;
                    case 'Transaction buy':    //交易    交易買入
                        if($v['num'] < 0){  //支出
                            $data['data'][$k]['send_address'] = $member->username;
                            $data['data'][$k]['receive_address'] = $sys_swap;
                            $data['data'][$k]['num'] = -$v['num'];
                        }else{  //收入
                            $data['data'][$k]['send_address'] = $sys_swap;
                            $data['data'][$k]['receive_address'] = $member->username;
                        }
                        break;
                    default:    //其他
                        if($v['num'] < 0){  //支出
                            $data['data'][$k]['send_address'] = $member->username;
                            $data['data'][$k]['receive_address'] = $sys_address;
                            $data['data'][$k]['num'] = -$v['num'];
                        }else{  //收入
                            $data['data'][$k]['send_address'] = $sys_address;
                            $data['data'][$k]['receive_address'] = $member->username;
                        }
                        break;
                }
                $data['data'][$k]['height'] = bcadd(14565,$v['id']);
                unset($data['data'][$k]['relation_id']);
                unset($data['data'][$k]['id']);
            }

        }

        $type_list = [];
        foreach (config('capital') as $k => $v){
            $type_list[$v[$this->language]] = $k;
        }
        $data['type'] =  $type_list;
        return api_success($data);

    }

    /**
     * 已领取 矿机产出
     */
    public function received(){
        //获取KR余额
        $wallet = MemberModel::wallet($this->mid)['waller'];
        //余额
        if($wallet[22]['money'] <= 0 && $wallet[22]['freeze_money'] <= 0 && $wallet[1]['money']) api_error('','Insufficient collection quantity',$this->language);
        // 启动事务
        Db::startTrans();
        try {

            if($wallet[22]['money'] > 0){
                $state = UserMoneyLogModel::change($this->mid,'KP',-$wallet[22]['money'],'withdrawal','','领取团队分红');
                if(!$state) api_error('','Withdrawal failed',$this->language);
            }
            if($wallet[1]['money'] > 0){
                $state = UserMoneyLogModel::change($this->mid,'USDT',-$wallet[1]['money'],'withdrawal','','领取团队分红');
                if(!$state) api_error('','Withdrawal failed',$this->language);
            }
            if($wallet[22]['freeze_money'] > 0){
                $state = UserMoneyLogModel::change($this->mid,'KP',-$wallet[22]['freeze_money'],'withdrawal','','领取矿机算力',2);
                if(!$state) api_error('','Withdrawal failed',$this->language);
            }
            //执行授权


            // 提交事务
            Db::commit();
            api_success();
        } catch (\Exception $e) {
            api_error('','Insufficient collection quantity',$this->language);
            // 回滚事务
            Db::rollback();
        }

        api_success();
    }

    /**
     * 用户授权领取分红
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function authorization_collection(){
        $type  = $this->request->post('type', 1, 'intval');

        $member = MemberModel::getDetails($this->mid);
        $wallet = MemberModel::wallet($this->mid)['waller'];
        //执行get请求外部连接
        if($type == 1){ //查询用户可领取USDT
            $AuthorizationInfo = ContractAuthorizationModel::where(['mid'=>$this->mid,'status'=>1,'cid'=>1])->find();
            if(!empty($AuthorizationInfo)) api_error('','No duplicate submissions within 5 minutes',$this->language);

            $money = $wallet[1]['money'];
            $url_name = 'setApprovalForUsdt';
        }
        if($type == 2){ //查询用户可领取KR
            $AuthorizationInfo = ContractAuthorizationModel::where(['mid'=>$this->mid,'status'=>1,'cid'=>1])->find();
            if(!empty($AuthorizationInfo)) api_error('','No duplicate submissions within 5 minutes',$this->language);

            $money = bcadd($wallet[22]['money'],$wallet[22]['freeze_money'],8);
            $url_name = 'setApprovalForKr';
        }
        //领取数量不得小于1
        if($money < 1) api_error('','The claimed quantity should not be less than 1',$this->language);

        //请求数据
        $options = [
            'form_params'   =>  ['address'=>$member['username'],'amount'=>$money],
        ];
        $headers = [
            'headers' => [
                'accept'=>'application/json',
                'content-type'=>'application/json',
                'sign'  =>  md5(env('HEADER_SIGN').'address:'.$member['username'].'amount:'.$money),
            ]
        ];
        
        // echo env('HEYUEURL_EMPOWER').$url_name;
        // die;
        
        $client = new \GuzzleHttp\Client($headers);
        $response = $client->request('POST', env('HEYUEURL_EMPOWER').$url_name, $options);
        $response_data = $response->getBody();
        $api_data = json_decode($response_data,true);
        //授权失败
        if($api_data['code'] == 0) api_error($api_data,'Authorization failed, please contact customer service',$this->language);
        if($type == 1){ //清空余额
            UserMoneyLogModel::change($this->mid,'USDT',-$money,'withdrawal','','用户领取USDT');
            ContractAuthorizationModel::add($this->mid,$member['username'],1,1,$money);

        }
        if($type == 2){ //清空余额
            if($wallet[22]['money'] > 0){
                UserMoneyLogModel::change($this->mid,'KR',-$wallet[22]['money'],'withdrawal','','用户领取');
                ContractAuthorizationModel::add($this->mid,$member['username'],22,2,$wallet[22]['money']);
            }
            if($wallet[22]['freeze_money'] > 0){
                UserMoneyLogModel::change($this->mid,'KR',-$wallet[22]['freeze_money'],'withdrawal','','用户领取',2);
                ContractAuthorizationModel::add($this->mid,$member['username'],22,2,$wallet[22]['freeze_money']);
            }
        }

        api_success($api_data['data']);
    }

}